package com.hxy.subscribe;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 订阅者
 */
public class SubThread {

    private final JedisPool jedisPool;
    private final Subscriber subscriber = new Subscriber();

    private final String channel = "MyChannel";

    public SubThread(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public void newsSubscription(String clientName) {
        System.out.println(String.format("【%s】订阅redis,频道 %s, 线程等待接收中...", clientName, channel));
        Jedis jedis = null;
        try {
            //取出一个连接
            jedis = jedisPool.getResource();
            //通过subscribe命令去订阅，入参是订阅者和频道名
            jedis.subscribe(subscriber, channel);
        } catch (Exception e) {
            System.out.println(String.format("订阅频道错误, %s", e));
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

}
